<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:xs="http://www.w3.org/2001/XMLSchema"
	exclude-result-prefixes="xs"
	version="1.0">
	
	<xsl:output method="xml"/>
	
	<xsl:template name="emitGroupQuery">
		<xsl:param name="groupList"/>
		
		<xsl:choose>
			<xsl:when test="string-length($groupList) = 0">
				<sql>select distinct thread_id 
					from group_thread</sql>
			</xsl:when>
			<xsl:otherwise>
				<sql>select distinct thread_id 
					from group_thread
					where group_id in (<xsl:value-of select="translate($groupList, ' ', ',')"/>)</sql>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>
	
	<xsl:template name="emitAuthorQuery">
		<xsl:param name="personList"/>
		
		<xsl:choose>
			<xsl:when test="string-length($personList) = 0">
				<sql>select distinct thread_id 
					from post</sql>
			</xsl:when>
			<xsl:otherwise>
				<sql>select distinct threadID
					from post
					where authorID in (<xsl:value-of select="translate($personList, ' ', ',')"/>)</sql>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>
	
	<xsl:template match="groups">
		<xsl:call-template name="emitGroupQuery">
			<xsl:with-param name="groupList" select="."/>
		</xsl:call-template>
	</xsl:template>
	
	<xsl:template match="authors">		
		<xsl:call-template name="emitAuthorQuery">
			<xsl:with-param name="personList" select="."/>
		</xsl:call-template>
	</xsl:template>
	
	<xsl:template match="sort">
		<sort><xsl:value-of select="."/></sort>
	</xsl:template>
	<xsl:template match="dates">
		<xsl:choose>
			<xsl:when test="range">
				<sql>select distinct threadID from post
					where (dateCreated &gt;= '<xsl:value-of select="range/low"/> 00:00:00') and 
					(dateCreated &lt;= '<xsl:value-of select="range/high"/> 23:59:59')</sql>
			</xsl:when>
			<xsl:when test="value">
				<xsl:choose>
					<xsl:when test="value/comparison = 'After'">
						<sql>select distinct threadID from post
							where (dateCreated &gt;= '<xsl:value-of select="value/value"/> 00:00:00')</sql> 
					</xsl:when>
					<xsl:when test="value/comparison = 'Before'">
						<sql>select distinct threadID from post
							where (dateCreated &lt;= '<xsl:value-of select="value/value"/> 23:59:59')</sql> 
					</xsl:when>
				</xsl:choose>
			</xsl:when>
		</xsl:choose>
	</xsl:template>

	<xsl:template match="view">
		<queries>
			<xsl:apply-templates select="groups"/>
			<xsl:apply-templates select="authors"/>
			<xsl:apply-templates select="dates"/>
			<xsl:apply-templates select="sort"/>
		</queries>
	</xsl:template>
	
</xsl:stylesheet>